<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>vue路由（十一） | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="Vue,">
  

  <meta name="description" content="一、路由基础介绍1.1 什么是前端路由 路由是根据不同的url地址展示不同的内容或页面 前端路由就是把不同的路由对应不同的内容或页面的任务交给前端来做，之前是通过服务端根据url的不同返回不同的页面实现的  1.2 什么时候使用前端路由 在单页面应用，大部分结构不变，只改变内容的使用  1.3 前端路由优点、缺点 优点： 用户体验好，不需要每次都从服务器全部获取，快速展现给用户   缺点： 不利于">
<meta name="keywords" content="Vue">
<meta property="og:type" content="article">
<meta property="og:title" content="vue路由（十一）">
<meta property="og:url" content="http://blog.poetries.top/2018/08/28/vue-router/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、路由基础介绍1.1 什么是前端路由 路由是根据不同的url地址展示不同的内容或页面 前端路由就是把不同的路由对应不同的内容或页面的任务交给前端来做，之前是通过服务端根据url的不同返回不同的页面实现的  1.2 什么时候使用前端路由 在单页面应用，大部分结构不变，只改变内容的使用  1.3 前端路由优点、缺点 优点： 用户体验好，不需要每次都从服务器全部获取，快速展现给用户   缺点： 不利于">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-08-15T04:25:31.938Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="vue路由（十一）">
<meta name="twitter:description" content="一、路由基础介绍1.1 什么是前端路由 路由是根据不同的url地址展示不同的内容或页面 前端路由就是把不同的路由对应不同的内容或页面的任务交给前端来做，之前是通过服务端根据url的不同返回不同的页面实现的  1.2 什么时候使用前端路由 在单页面应用，大部分结构不变，只改变内容的使用  1.3 前端路由优点、缺点 优点： 用户体验好，不需要每次都从服务器全部获取，快速展现给用户   缺点： 不利于">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、路由基础介绍"><span class="toc-text">一、路由基础介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-什么是前端路由"><span class="toc-text">1.1 什么是前端路由</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-什么时候使用前端路由"><span class="toc-text">1.2 什么时候使用前端路由</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-前端路由优点、缺点"><span class="toc-text">1.3 前端路由优点、缺点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、vue-router用来构建SPA"><span class="toc-text">二、vue-router用来构建SPA</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-开始"><span class="toc-text">2.1 开始</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-动态路由匹配"><span class="toc-text">2.2 动态路由匹配</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-嵌套路由"><span class="toc-text">2.3 嵌套路由</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-编程式路由"><span class="toc-text">2.4 编程式路由</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-5-命名路由"><span class="toc-text">2.5 命名路由</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-6-命名视图"><span class="toc-text">2.6 命名视图</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-7-重定向和别名"><span class="toc-text">2.7 重定向和别名</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-8-列表进入详情页传参"><span class="toc-text">2.8 列表进入详情页传参</span></a></li></ol></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-vue-router" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">vue路由（十一）</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.08.28</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 2.2k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 9分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、路由基础介绍"><a href="#一、路由基础介绍" class="headerlink" title="一、路由基础介绍"></a>一、路由基础介绍</h2><h3 id="1-1-什么是前端路由"><a href="#1-1-什么是前端路由" class="headerlink" title="1.1 什么是前端路由"></a>1.1 什么是前端路由</h3><ul>
<li>路由是根据不同的<code>url</code>地址展示不同的内容或页面</li>
<li>前端路由就是把不同的路由对应不同的内容或页面的任务交给前端来做，之前是通过服务端根据<code>url</code>的不同返回不同的页面实现的</li>
</ul>
<h3 id="1-2-什么时候使用前端路由"><a href="#1-2-什么时候使用前端路由" class="headerlink" title="1.2 什么时候使用前端路由"></a>1.2 什么时候使用前端路由</h3><ul>
<li>在单页面应用，大部分结构不变，只改变内容的使用</li>
</ul>
<h3 id="1-3-前端路由优点、缺点"><a href="#1-3-前端路由优点、缺点" class="headerlink" title="1.3 前端路由优点、缺点"></a>1.3 前端路由优点、缺点</h3><ul>
<li><strong>优点</strong>：<ul>
<li>用户体验好，不需要每次都从服务器全部获取，快速展现给用户</li>
</ul>
</li>
<li><strong>缺点</strong>：<ul>
<li>不利于<code>SEO</code></li>
<li>使用浏览器的前进，后退键的时候会重新发送请求，没有合理的利用缓存</li>
<li>单页面无法记住之前滚动的位置，无法再前进，后退的时候记住滚动的位置</li>
</ul>
</li>
</ul>
<h2 id="二、vue-router用来构建SPA"><a href="#二、vue-router用来构建SPA" class="headerlink" title="二、vue-router用来构建SPA"></a>二、vue-router用来构建SPA</h2><h3 id="2-1-开始"><a href="#2-1-开始" class="headerlink" title="2.1 开始"></a>2.1 开始</h3><blockquote>
<p>在你的文件夹下的 <code>src</code> 文件夹下的 <code>main.js</code> 文件内写入以下代码</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span></span><br><span class="line"><span class="keyword">import</span> VueRouter <span class="keyword">from</span> <span class="string">'vue-router'</span></span><br><span class="line"></span><br><span class="line">Vue.use(VueRouter)</span><br></pre></td></tr></table></figure>
<blockquote>
<ul>
<li><code>vue-router</code>其实就是对<code>history</code>的封装</li>
<li>地址后面跟<code>#</code>其实就是用了<code>hash</code></li>
</ul>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"box"</span>&gt;</span> </span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--定义模版--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">template</span> <span class="attr">id</span>=<span class="string">"a"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">        第一个router</span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">template</span> <span class="attr">id</span>=<span class="string">"b"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">        第二个router</span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> routes = [</span><br><span class="line">    &#123;</span><br><span class="line">        path:<span class="string">"/one"</span>,</span><br><span class="line"></span><br><span class="line">        component:&#123;<span class="attr">template</span>:<span class="string">"#a"</span>&#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        path:<span class="string">"/two"</span>,</span><br><span class="line">        component:&#123;<span class="attr">template</span>:<span class="string">"#b"</span>&#125;</span><br><span class="line">    &#125;,</span><br><span class="line">];</span><br><span class="line"><span class="comment">// 定义路由组件</span></span><br><span class="line"><span class="keyword">var</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">    routes</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 定义路由</span></span><br><span class="line"><span class="keyword">new</span> Vue(&#123;</span><br><span class="line">    el:<span class="string">"#box"</span>,</span><br><span class="line">    router</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 创建和挂载实例</span></span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"box"</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/one"</span>&gt;</span>One<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/two"</span>&gt;</span>Two<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">router-view</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>&lt; router-link &gt;</code> 默认会被渲染成一个 <code>&lt;a&gt;</code> 标签 <code>to=&quot;&quot;</code>为我们定义的路由</li>
<li><code>&lt; router-view &gt;</code> 路由匹配到的组件将渲染在这里</li>
</ul>
<ul>
<li>在<code>new Router</code>中指定<code>mode</code>为<code>history</code>即可去掉<code>#</code>，这样加载更加逼真符合预期</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">new</span> Router(&#123;</span><br><span class="line">    mode: <span class="string">"history"</span>,</span><br><span class="line">    routes: []</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//router-link跳转标签 当a标签使用，to必须是一个绝对地址</span></span><br><span class="line">&lt;router-link to=<span class="string">"/goods/title"</span>&gt;&lt;<span class="regexp">/router-link&gt;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">/</span><span class="regexp">/或者</span></span><br><span class="line"><span class="regexp">this.$router.push(&#123;path:""&#125;)</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">/</span><span class="regexp">/ 组件的渲染 配合router—link使用</span></span><br><span class="line"><span class="regexp">&lt;router-view&gt;&lt;/</span>router-view&gt;</span><br></pre></td></tr></table></figure>
<h3 id="2-2-动态路由匹配"><a href="#2-2-动态路由匹配" class="headerlink" title="2.2 动态路由匹配"></a>2.2 动态路由匹配</h3><blockquote>
<p>通过变化的地址去加载信息</p>
</blockquote>
<table>
<thead>
<tr>
<th>模式</th>
<th>匹配路径</th>
<th><code>$route.params</code></th>
</tr>
</thead>
<tbody>
<tr>
<td><code>/user/:username</code></td>
<td><code>/user/poetries</code></td>
<td><code>{username:&quot;poetries&quot;}</code></td>
</tr>
<tr>
<td><code>/user/:username/post/:post_id</code></td>
<td><code>/user/poetries/post/123</code></td>
<td><code>{username:&quot;evan&quot;,post_id:123}</code></td>
</tr>
</tbody>
</table>
<ul>
<li>应用场景<ul>
<li>商城的详情页，要变换商品的<code>id</code>，根据商品的<code>id</code>去查对应商品的信息</li>
</ul>
</li>
</ul>
<h3 id="2-3-嵌套路由"><a href="#2-3-嵌套路由" class="headerlink" title="2.3 嵌套路由"></a>2.3 嵌套路由</h3><ul>
<li>什么是嵌套路由<ul>
<li>路由嵌套路由</li>
</ul>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">new</span> Router(&#123;</span><br><span class="line">    mode: <span class="string">"history"</span>,</span><br><span class="line">    routes: [</span><br><span class="line">        &#123;</span><br><span class="line">            path:<span class="string">"/goods"</span>, </span><br><span class="line">            name: <span class="string">"GoodsList"</span>,</span><br><span class="line">            component:GoodsList,</span><br><span class="line">            children: [ <span class="comment">// 定义子组件</span></span><br><span class="line">               &#123;</span><br><span class="line">                   path:<span class="string">"title"</span>,<span class="comment">//最后形式/goods/title</span></span><br><span class="line">                   name:<span class="string">"title"</span>,</span><br><span class="line">                   component:Title</span><br><span class="line">               &#125;</span><br><span class="line">            ]</span><br><span class="line">        &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="2-4-编程式路由"><a href="#2-4-编程式路由" class="headerlink" title="2.4 编程式路由"></a>2.4 编程式路由</h3><blockquote>
<p>通过js来实现页面的跳转</p>
</blockquote>
<ul>
<li>通过<code>push</code>名字就可以实现页面的跳转</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 方式一</span></span><br><span class="line"><span class="keyword">this</span>.$router.push(<span class="string">"name"</span>) <span class="comment">//name /cart</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方式二 </span></span><br><span class="line"><span class="keyword">this</span>.$router.push(&#123;<span class="attr">path</span>:<span class="string">"name"</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方式三 传递参数</span></span><br><span class="line"><span class="keyword">this</span>.$router.push(&#123;<span class="attr">path</span>:<span class="string">"name?a=123"</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 或者</span></span><br><span class="line"><span class="keyword">this</span>.$router.push(&#123;<span class="attr">path</span>:<span class="string">"name"</span>,<span class="attr">query</span>:&#123;<span class="attr">a</span>:<span class="number">123</span>&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方式四 </span></span><br><span class="line"><span class="keyword">this</span>.$router.go(<span class="number">1</span>) <span class="comment">//$router其实就是对history的封装</span></span><br></pre></td></tr></table></figure>
<ul>
<li>如何拿到传递过来的参数</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">this</span>.$router.push(<span class="string">"/cart?goodsId=123"</span>)</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--如何在页面上拿到goodsId--&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">span</span>&gt;</span>&#123;&#123;$.route.query.goodsId&#125;&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>$route.params</code>是组件跟组件之间路由切换的时候，参数传递</li>
</ul>
<h3 id="2-5-命名路由"><a href="#2-5-命名路由" class="headerlink" title="2.5 命名路由"></a>2.5 命名路由</h3><blockquote>
<p>有时我们通过一个名称来标识一个路由显得更方便一些，特别是在链接一个路由，或者是执行一些跳转的时候。你可以在创建 <code>Router</code> 实例的时候，在 <code>routes</code> 配置中给某个路由设置名称</p>
</blockquote>
<blockquote>
<ul>
<li>给路由定义不同的名字，根据名字进行匹配</li>
<li>给不同的<code>router-view</code>定义名字，通过名字进行对应组件渲染</li>
</ul>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">new</span> Router(&#123;</span><br><span class="line">    mode: <span class="string">"history"</span>,</span><br><span class="line">    routes: [</span><br><span class="line">        &#123;</span><br><span class="line">            path:<span class="string">"/cart/:cartId"</span>, </span><br><span class="line">            name: <span class="string">"cart"</span>,</span><br><span class="line">            component:GoodsList,</span><br><span class="line">        &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<ul>
<li>之前的跳转方式</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/cart"</span>&gt;</span><span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>根据路由名字跳转。以下是一个命名的路由，而且还带了参数</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">v-bind:to</span>=<span class="string">"&#123;&#123;name:'cart',params:&#123;cartId:123&#125;&#125;&#125;"</span>&gt;</span><span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--params是路由的参数，并不是页面之间跳转的参数--&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="2-6-命名视图"><a href="#2-6-命名视图" class="headerlink" title="2.6 命名视图"></a>2.6 命名视图</h3><blockquote>
<p>有时候想同时（同级）展示多个视图，而不是嵌套展示，例如创建一个布局，有 <code>·sidebar·</code>（侧导航） 和<code>main</code>（主内容） 两个视图，这个时候命名视图就派上用场了。你可以在界面中拥有多个单独命名的视图，而不是只有一个单独的出口。如果 <code>router-view</code> 没有设置名字，那么默认为 <code>default</code></p>
</blockquote>
<ul>
<li>实现一个命名的视图（很少用到）<ul>
<li>给<code>router-view</code>加<code>name</code>值</li>
</ul>
</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">router-view</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">router-view</span> <span class="attr">name</span>=<span class="string">"title"</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">router-view</span> <span class="attr">name</span>=<span class="string">"image"</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>页面一进来就加载三个<code>router-view</code>。实现方法</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">new</span> Router(&#123;</span><br><span class="line">    mode: <span class="string">"history"</span>,</span><br><span class="line">    routes: [</span><br><span class="line">        &#123;</span><br><span class="line">            path:<span class="string">"/"</span>, </span><br><span class="line">            name: <span class="string">"cart"</span>,</span><br><span class="line">            <span class="comment">// 根据不同的name值去加载对应的router-view,映射到对应的组件</span></span><br><span class="line">            components:&#123;</span><br><span class="line">                <span class="keyword">default</span>:GoodsList,</span><br><span class="line">                title:Title,</span><br><span class="line">                img:Image</span><br><span class="line">            &#125;,</span><br><span class="line">            path:<span class="string">"/cart/:cartId"</span>, </span><br><span class="line">            name: <span class="string">"cart"</span>,</span><br><span class="line">            component:Cart</span><br><span class="line">        &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">router-view</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">router-view</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>当我们的视图如上时,我们会发现每一个路由被渲染了两次,所以我们需要为视图命名</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">router-view</span> <span class="attr">name</span>=<span class="string">"a"</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">router-view</span> <span class="attr">name</span>=<span class="string">"b"</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br><span class="line">```    </span><br><span class="line"></span><br><span class="line">```javascript</span><br><span class="line">var Foo = &#123; template: '<span class="tag">&lt;<span class="name">div</span>&gt;</span>foo<span class="tag">&lt;/<span class="name">div</span>&gt;</span>' &#125;</span><br><span class="line">var Bar = &#123; template: '<span class="tag">&lt;<span class="name">div</span>&gt;</span>bar<span class="tag">&lt;/<span class="name">div</span>&gt;</span>' &#125;</span><br><span class="line">var routes = [</span><br><span class="line">        &#123;</span><br><span class="line">            path:"/one",</span><br><span class="line">            name:"one",</span><br><span class="line">            components:&#123;</span><br><span class="line">                a:Foo,</span><br><span class="line">                b:Bar</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">    ]</span><br></pre></td></tr></table></figure>
<h3 id="2-7-重定向和别名"><a href="#2-7-重定向和别名" class="headerlink" title="2.7 重定向和别名"></a>2.7 重定向和别名</h3><p><strong>重定向</strong></p>
<blockquote>
<p>重定向(<code>Redirect</code>)就是通过各种方法将各种网络请求重新定个方向转到其它位置,用于网站调整或网页被移到一个新地址,它也是通过 <code>routes</code> 配置来完成，下面例子是从 <code>/a</code> 重定向到 <code>/b</code></p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  routes: [</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">'/a'</span>, <span class="attr">redirect</span>: <span class="string">'/b'</span> &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p><strong>别名</strong></p>
<blockquote>
<p><code>/a</code> 的别名是 <code>/b</code>，意味着，当用户访问<code>/b</code> 时，<code>URL</code> 会保持为 <code>/b</code>，但是路由匹配则为 <code>/a</code>，就像用户访问<code>/a</code> 一样。简单的说就是给 /a 起了一个外号叫做 <code>/b</code> ,但是本质上还是 <code>/a</code></p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  routes: [</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">'/a'</span>, <span class="attr">component</span>: A, <span class="attr">alias</span>: <span class="string">'/b'</span> &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="2-8-列表进入详情页传参"><a href="#2-8-列表进入详情页传参" class="headerlink" title="2.8 列表进入详情页传参"></a>2.8 列表进入详情页传参</h3><blockquote>
<p>例如商品列表页面前往商品详情页面，需要传一个商品id</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">:to</span>=<span class="string">"&#123;path: 'detail', query: &#123;id: 1&#125;&#125;"</span>&gt;</span>前往detail页面<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>c</code>页面的路径为<code>http://localhost:8080/#/detail?id=1</code>，可以看到传了一个参数<code>id=1</code>，并且就算刷新页面id也还会存在。此时在c页面可以通过id来获取对应的详情数据，获取<code>id</code>的方式是<code>this.$route.query.id</code></p>
</blockquote>
<p><strong>vue传参方式有：query、params+动态路由传参</strong></p>
<blockquote>
<p><code>query</code>通过<code>path</code>切换路由，<code>params</code>通过<code>name</code>切换路由</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">// query通过path切换路由</span><br><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">:to</span>=<span class="string">"&#123;path: 'Detail', query: &#123; id: 1 &#125;&#125;"</span>&gt;</span>前往Detail页面<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line">// params通过name切换路由</span><br><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">:to</span>=<span class="string">"&#123;name: 'Detail', params: &#123; id: 1 &#125;&#125;"</span>&gt;</span>前往Detail页面<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>query</code>通过<code>this.$route.query</code>来接收参数，<code>params</code>通过<code>this.$route.params</code>来接收参数</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// query通过this.$route.query接收参数</span></span><br><span class="line">created () &#123;</span><br><span class="line">    <span class="keyword">const</span> id = <span class="keyword">this</span>.$route.query.id;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// params通过this.$route.params来接收参数</span></span><br><span class="line">created () &#123;</span><br><span class="line">    <span class="keyword">const</span> id = <span class="keyword">this</span>.$route.params.id;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>query</code>传参的<code>url</code>展现方式：<code>/detail?id=1&amp;user=123&amp;identity=1&amp;</code>更多参数</li>
<li><code>params</code>＋动态路由的<code>url</code>方式：<code>/detail/123</code></li>
<li><code>params</code>动态路由传参，一定要在路由中定义参数，然后在路由跳转的时候必须要加上参数，否则就是空白页面</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&#123;      </span><br><span class="line">    path: &apos;/detail/:id&apos;,      </span><br><span class="line">    name: &apos;Detail&apos;,      </span><br><span class="line">    component: Detail    </span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>注意</strong>，<code>params</code>传参时，如果没有在路由中定义参数，也是可以传过去的，同时也能接收到，但是一旦刷新页面，这个参数就不存在了。这对于需要依赖参数进行某些操作的行为是行不通的</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">// 定义的路由中，只定义一个id参数</span><br><span class="line">&#123;</span><br><span class="line">    path: 'detail/:id',</span><br><span class="line">    name: 'Detail',</span><br><span class="line">    components: Detail</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// template中的路由传参，</span><br><span class="line">// 传了一个id参数和一个token参数</span><br><span class="line">// id是在路由中已经定义的参数，而token没有定义</span><br><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">:to</span>=<span class="string">"&#123;name: 'Detail', params: &#123; id: 1, token: '123456' &#125;&#125;"</span>&gt;</span>前往Detail页面<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line"></span><br><span class="line">// 在详情页接收</span><br><span class="line">created () &#123;</span><br><span class="line">    // 以下都可以正常获取到</span><br><span class="line">    // 但是页面刷新后，id依然可以获取，而token此时就不存在了</span><br><span class="line">    const id = this.$route.params.id;</span><br><span class="line">    const token = this.$route.params.token;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/08/28/vue-computed-watch/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/08/28/vue-axios/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
